package homework8;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Translation extends JFrame {

	private JPanel contentPane;
	private LinkedList<Record> dic;
	private JTextField rawString;
	private JButton btnTsl;
	private JTextArea tslArea;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Translation frame = new Translation();
					frame.setVisible(true);
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Translation() {
		createContents();
	}
	private void createContents() {
		//
		dic=new LinkedList<Record>();
		Record[] i= {new Record("life","生活"),new Record("will","将会"),new Record("change","改变")};
		for(Record x:i) {
			dic.add(x);
		}
		//
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		rawString = new JTextField();
		rawString.setBounds(87, 42, 213, 21);
		contentPane.add(rawString);
		rawString.setColumns(10);
		
		btnTsl = new JButton("Translate it.");
		btnTsl.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String regexAlpha="[a-zA-Z]+";
				String regexCha="[\\u4e00-\\u9fa5]+";
				String raw=rawString.getText();
				Boolean flag=true;
				if(raw.matches(regexAlpha)) {//是字母
					Iterator<Record> iter=dic.iterator();
					while(iter.hasNext()) {
						raw=raw.toLowerCase();
						Record tmp=iter.next();
						if(tmp.eng.equals(raw)) {
							flag=false;
							tslArea.setText(tmp.chn);
						}
					}
				}
				else if(raw.matches(regexCha)) {//是汉字
					Iterator<Record> iter=dic.iterator();
					while(iter.hasNext()) {
						Record tmp=iter.next();
						if(tmp.chn.equals(raw)) {
							flag=false;
							tslArea.setText(tmp.eng);
							
							
						}
					}
				}
				else {
					flag=false;
					tslArea.setText("类型错误。");
				}
				if(flag) {
					tslArea.setText("未找到。");
				}
			}
		});
		btnTsl.setBounds(87, 73, 213, 23);
		contentPane.add(btnTsl);
		
		tslArea = new JTextArea();
		tslArea.setBounds(87, 155, 213, 78);
		contentPane.add(tslArea);
	}
}
